import React from "react";
import { useAuth } from "context/auth-context";
import { Form, Input, Button } from "antd";
import { useAsync } from "hooks";

const Register: React.FC<{
  onError: (error: Error | null) => void;
}> = ({ onError }) => {
  const { register } = useAuth();
  const { run, isLoading } = useAsync();

  const handleSubmit = async ({
    cpassword,
    ...values
  }: {
    username: string;
    password: string;
    cpassword: string;
  }) => {
    if (values.password && cpassword !== values.password) {
      return onError(new Error("请确认两次输入的密码是否一致"));
    }

    if (cpassword) onError(null);

    try {
      await run(register(values));
    } catch (error) {
      onError(error);
    }
  };

  return (
    <Form onFinish={handleSubmit}>
      <Form.Item
        name="username"
        rules={[{ required: true, message: "请输入用户名" }]}
      >
        <Input placeholder="用户名" />
      </Form.Item>
      <Form.Item
        name="password"
        rules={[{ required: true, message: "请输入密码" }]}
      >
        <Input placeholder="密码" />
      </Form.Item>
      <Form.Item
        name="cpassword"
        rules={[{ required: true, message: "请输入确认密码" }]}
      >
        <Input placeholder="确认密码" />
      </Form.Item>
      <Form.Item>
        <Button
          style={{ width: "100%" }}
          type="primary"
          htmlType="submit"
          loading={isLoading}
        >
          注册
        </Button>
      </Form.Item>
    </Form>
  );
};

export default Register;
